using System;
using System.Linq;
using System.Data;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Widgetsphere.Core.DataAccess;
using Widgetsphere.Core.Util;
using Widgetsphere.Core.Logging;
using Widgetsphere.Core.Exceptions;
using ACME.Northwind.Business;
using ACME.Northwind.Business.Objects;
using ACME.Northwind.Business.Rules;
using ACME.Northwind.Business.SelectCommands;
using System.IO;
using System.Data.SqlClient;

namespace ACME.Northwind.Domain.Objects
{
	#region internal class
	/// <summary>
	/// This is an customizable extender for the domain class associated with the 'Supplier' object collection
	/// </summary>
	[Serializable()]
	[System.ComponentModel.DesignerCategoryAttribute("code")]
	partial class DomainSupplierCollection : PersistableDomainCollectionBase, IEnumerable, ISerializable, IDisposable
	{
		#region Member Variables

		//Generated Relationships This Object Plays Parent Role
		internal bool ProductFilled = false;


		#endregion

		#region ISerializable Members
		/// <summary>
		/// Serialization constructor
		/// </summary>
		protected DomainSupplierCollection(SerializationInfo info, StreamingContext context):this()
		{
			ProductFilled = (bool)info.GetValue("ProductFilled", typeof(bool));

		}

		/// <summary>
		/// Method used internally for serialization
		/// </summary>
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			info.AddValue("ProductFilled", ProductFilled);

		}
		#endregion

		#region Properties

		internal SubDomain SubDomain
		{
			get{ return (SubDomain)this.DataSet; }
		}

		internal string Modifier
		{
			get{ return SubDomain.Modifier; }
		}

		internal virtual DataRelation SupplierProductRelation
		{
			get
			{
				if(!this.ProductFilled)
				{
					ProductSelectBySupplierPks retrieveRule = new ProductSelectBySupplierPks();
					this.SubDomain.AddSelectCommand(retrieveRule);
					this.SubDomain.RunSelectCommands();
				}
				return this.SubDomain.Relations["SupplierProductRelation"];
			}
		}

		//Generate Property Access To Related Tables
		internal virtual DomainProductCollection RelatedProductCollection
		{
			get { return (DomainProductCollection)this.SubDomain.GetDomainCollection(Collections.ProductCollection); }
		}

		//Generated Domain Properties Where This Object Plays Both Roles

		#endregion

		#region Contructors /Initialization

		internal DomainSupplierCollection()
		{
			try
			{
				base.TableName = "SupplierCollection";
				this.InitClass();
			}
			catch (System.Data.DBConcurrencyException dbcex) { throw new ConcurrencyException(GlobalValues.ERROR_CONCURRENCY_FAILURE, dbcex); }
			catch (System.Data.SqlClient.SqlException sqlexp) { if (sqlexp.Number == 547 || sqlexp.Number == 2627) throw new UniqueConstraintViolatedException(GlobalValues.ERROR_CONSTRAINT_FAILURE, sqlexp); else throw; }
			catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); throw; }
		}

		private void InitClass() 
		{
			BeginInit();
			this.columnSupplierId = new DataColumn("SupplierID", typeof(int), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnSupplierId);
			this.columnSupplierId.AllowDBNull = false;
			this.columnSupplierId.AutoIncrement = true;
			this.columnSupplierId.AutoIncrementSeed = -1;
			this.columnSupplierId.AutoIncrementStep = -1;
			this.columnSupplierId.Caption = "";
			this.columnRegion = new DataColumn("Region", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnRegion);
			this.columnRegion.Caption = "";
			this.columnPostalCode = new DataColumn("PostalCode", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnPostalCode);
			this.columnPostalCode.Caption = "";
			this.columnPhone = new DataColumn("Phone", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnPhone);
			this.columnPhone.Caption = "";
			this.columnHomePage = new DataColumn("HomePage", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnHomePage);
			this.columnHomePage.Caption = "";
			this.columnFax = new DataColumn("Fax", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnFax);
			this.columnFax.Caption = "";
			this.columnCountry = new DataColumn("Country", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnCountry);
			this.columnCountry.Caption = "";
			this.columnContactTitle = new DataColumn("ContactTitle", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnContactTitle);
			this.columnContactTitle.Caption = "";
			this.columnContactName = new DataColumn("ContactName", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnContactName);
			this.columnContactName.Caption = "";
			this.columnCompanyName = new DataColumn("CompanyName", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnCompanyName);
			this.columnCompanyName.AllowDBNull = false;
			this.columnCompanyName.DefaultValue = "";
			this.columnCompanyName.Caption = "";
			this.columnCity = new DataColumn("City", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnCity);
			this.columnCity.Caption = "";
			this.columnAddress = new DataColumn("Address", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnAddress);
			this.columnAddress.Caption = "";
			this.columnModifiedBy = new DataColumn("ModifiedBy", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnModifiedBy);
			this.columnModifiedDate = new DataColumn("ModifiedDate", typeof(DateTime), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnModifiedDate);
			this.columnCreatedBy = new DataColumn("CreatedBy", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnCreatedBy);
			this.columnCreatedDate = new DataColumn("CreatedDate", typeof(DateTime), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnCreatedDate);
			this.columnTimeStamp = new DataColumn("TimeStamp", typeof(System.Byte[]), null, System.Data.MappingType.Element);
			base.Columns.Add(this.columnTimeStamp);
			base.Constraints.Add(new UniqueConstraint("PrimaryKey", new DataColumn[] {this.columnSupplierId}, true));
			EndInit();
		}

		private bool mModifyUpdateOn = true;

		/// <summary>
		/// Raises the RowChanged event.
		/// </summary>
		protected override void OnRowChanged(DataRowChangeEventArgs e)
		{
			base.OnRowChanged(e);
			if(e.Action == DataRowAction.Change && mModifyUpdateOn)
			{
				mModifyUpdateOn = false;
				if ((e.Row[this.ModifiedByColumn] == System.DBNull.Value) || ((string)e.Row[this.ModifiedByColumn] != this.Modifier)) e.Row[this.ModifiedByColumn] = this.Modifier;
				mModifyUpdateOn = true;
			}
		}

		#endregion

		#region Database Retrieval

		internal DomainSupplier NewItem()
		{
			DomainSupplier retval = (DomainSupplier)(base.NewRow());
			((DataRow)retval)[ModifiedByColumn] = this.Modifier;
			((DataRow)retval)[ModifiedDateColumn] = DateTime.Now;
			((DataRow)retval)[CreatedByColumn] = this.Modifier;
			((DataRow)retval)[CreatedDateColumn] = DateTime.Now;

			return retval;
		}

		internal DomainSupplier NewItem(int supplierid)
		{
			DomainSupplier retval = (DomainSupplier)(base.NewRow());
			((DataRow)retval)["SupplierID"] = supplierid;
			((DataRow)retval)[ModifiedByColumn] = this.Modifier;
			((DataRow)retval)[ModifiedDateColumn] = DateTime.Now;
			((DataRow)retval)[CreatedByColumn] = this.Modifier;
			((DataRow)retval)[CreatedDateColumn] = DateTime.Now;

			return retval;
		}

		internal void AddItem(DomainSupplier item)
		{
			base.Rows.Add(item);
		}

		internal void InsertAtSupplier(DomainSupplier item, int pos)
		{
			base.Rows.InsertAt(item, pos);
		}

		internal virtual void Persist()
		{
			this.SubDomain.Persist();
		}

		#region Select Methods

		internal static DomainSupplierCollection RunSelect(SupplierSearch search, string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new SupplierSelectBySearch(search));
			sd.RunSelectCommands();
			return (DomainSupplierCollection)sd.GetDomainCollection(Collections.SupplierCollection);
		}

		internal static DomainSupplierCollection RunSelect(SupplierSearch search, SupplierPaging paging, string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			SupplierSelectBySearch command = new SupplierSelectBySearch(search, paging);
			sd.AddSelectCommand(command);
			sd.RunSelectCommands();
			paging.RecordCount = command.Count;
			return (DomainSupplierCollection)sd.GetDomainCollection(Collections.SupplierCollection);
		}

		internal static DomainSupplierCollection RunSelect(string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new SupplierSelectAll());
			sd.RunSelectCommands();
			return (DomainSupplierCollection)sd.GetDomainCollection(Collections.SupplierCollection);
		}

		internal static DomainSupplierCollection RunSelect(int page, int pageSize, string orderByColumn, bool ascending, string filter, out int count, string modifier)
		{
			DomainSupplierCollection returnVal = null;
			SubDomain sd = new SubDomain(modifier);
			SupplierPagedSelect retrieveRule = new SupplierPagedSelect(page, pageSize, PersistableDomainCollectionBase.DataColumnNameToParameterName(orderByColumn), ascending, filter);
			sd.AddSelectCommand(retrieveRule);
			sd.RunSelectCommands();
			returnVal = (DomainSupplierCollection)sd.GetDomainCollection(Collections.SupplierCollection);
			count = retrieveRule.Count;
			return returnVal;
		}

		internal static DomainSupplierCollection SelectBySupplierPks(List<SupplierPrimaryKey> primaryKeys, string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new SupplierSelectByPks(primaryKeys));
			sd.RunSelectCommands();
			return (DomainSupplierCollection)sd.GetDomainCollection(Collections.SupplierCollection);
		}

		#endregion

		#endregion

		#region DomainSupplier Collection Methods
		internal void RemoveSupplier(DomainSupplier item) 
		{
			base.Rows.Remove(item);
		}

		internal virtual int Count 
		{
			get { return base.Rows.Count; }
		}

		/// <summary>
		/// Returns an enumerator that can be used to iterate through the collection.
		/// </summary>
		/// <returns>An Enumerator that can iterate through the objects in this collection.</returns>
		public virtual System.Collections.IEnumerator GetEnumerator() 
		{
			return base.Rows.GetEnumerator();
		}

		/// <summary>
		/// Gets or sets the element at the specified index.
		/// </summary>
		/// <param name="index">The zero-based index of the element to get or set. </param>
		/// <returns>The element at the specified index.</returns>
		internal DomainSupplier this[int index] 
		{
			get { return ((DomainSupplier)(base.Rows[index])); }
		}

		internal DomainSupplier GetSupplier(int supplierid)
		{
			return ((DomainSupplier)(base.Rows.Find(new object[] {supplierid})));
		}

		#endregion

		#region Data Columns Setup
		protected DataColumn columnSupplierId;
		protected DataColumn columnRegion;
		protected DataColumn columnPostalCode;
		protected DataColumn columnPhone;
		protected DataColumn columnHomePage;
		protected DataColumn columnFax;
		protected DataColumn columnCountry;
		protected DataColumn columnContactTitle;
		protected DataColumn columnContactName;
		protected DataColumn columnCompanyName;
		protected DataColumn columnCity;
		protected DataColumn columnAddress;
		protected DataColumn columnCreatedBy;
		protected DataColumn columnCreatedDate;
		protected DataColumn columnModifiedBy;
		protected DataColumn columnModifiedDate;
		protected DataColumn columnTimeStamp;
		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn SupplierIdColumn 
		{
			get { return this.columnSupplierId; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn RegionColumn 
		{
			get { return this.columnRegion; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn PostalCodeColumn 
		{
			get { return this.columnPostalCode; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn PhoneColumn 
		{
			get { return this.columnPhone; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn HomePageColumn 
		{
			get { return this.columnHomePage; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn FaxColumn 
		{
			get { return this.columnFax; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn CountryColumn 
		{
			get { return this.columnCountry; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn ContactTitleColumn 
		{
			get { return this.columnContactTitle; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn ContactNameColumn 
		{
			get { return this.columnContactName; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn CompanyNameColumn 
		{
			get { return this.columnCompanyName; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn CityColumn 
		{
			get { return this.columnCity; }
		}

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn AddressColumn 
		{
			get { return this.columnAddress; }
		}

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn ModifiedDateColumn 
		{
			get { return this.columnModifiedDate; }
		}

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn ModifiedByColumn 
		{
			get { return this.columnModifiedBy; }
		}

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn CreatedDateColumn 
		{
			get { return this.columnCreatedDate; }
		}

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn CreatedByColumn 
		{
			get { return this.columnCreatedBy; }
		}

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn TimeStampColumn 
		{
			get { return this.columnTimeStamp; }
		}

		#endregion

		#region Protected Overrides

		/// <summary>
		/// Create a new instance of this object type
		/// </summary>
		protected override DataTable CreateInstance()
		{
			return new DomainSupplierCollection();
		}

		/// <summary>
		/// Create new row from a DataRowBuilder
		/// </summary>
		/// <param name="builder">The DataRowBuilder object that is used to create the new row</param>
		/// <returns>A new datarow of type 'Supplier'</returns>
		protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
		{
			DomainSupplier retval = new DomainSupplier(builder);
			return retval;
		}

		/// <summary>
		/// Returns the type of the datarow that this collection holds
		/// </summary>
		protected override System.Type GetRowType() 
		{
			return typeof(DomainSupplier);
		}
		#endregion

		#region Implement Persistable Table Abstact Methods

		/// <summary>
		/// Gets a list of parameters for SQL update commands.
		/// </summary>
		protected override List<IDbDataParameter> GetUpdateFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Gets a list of parameters for SQL insert commands.
		/// </summary>
		protected override List<IDbDataParameter> GetInsertFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Gets a list of parameters for SQL delete commands.
		/// </summary>
		protected override List<IDbDataParameter> GetDeleteFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Determines if the stored procedure or SQL text is used for CRUD operations.
		/// </summary>
		protected override bool UseStoredProcedure
		{
			get { return true; }
		}

		/// <summary>
		/// The stored procedure name that performs deletes for the objects in this collection
		/// </summary>
		protected override string DeleteStoredProcedureName
		{
			get { return "gen_SupplierDelete"; }
		}

		/// <summary>
		/// The SQL that performs deletes for the objects in this collection
		/// </summary>
		protected override string DeleteSQLText
		{
			get { return null; }
		}

		/// <summary>
		/// The stored procedure name that performs inserts for the objects in this collection
		/// </summary>
		protected override string InsertStoredProcedureName
		{
			get { return "gen_SupplierInsert"; }
		}

		/// <summary>
		/// The SQL that performs inserts for the objects in this collection
		/// </summary>
		protected override string InsertSQLText
		{
			get { return null; }
		}

		/// <summary>
		/// The stored procedure name that performs updates for the objects in this collection
		/// </summary>
		protected override string UpdateStoredProcedureName
		{
			get { return "gen_SupplierUpdate"; }
		}

		/// <summary>
		/// The SQL that performs updates for the objects in this collection
		/// </summary>
		protected override string UpdateSQLText
		{
			get { return null; }
		}

		public override void SetChildSelectedFalse()
		{
			ProductFilled = false;
		}

		/// <summary>
		/// Creates the referential integrity for this collection
		/// </summary>
		public override void CreateRelations()
		{
			if(!SubDomain.Relations.Contains("SupplierProductRelation"))
			{
				if(SubDomain.Contains(Collections.ProductCollection))
				{
					DataRelation supplierProductRelation = new DataRelation("SupplierProductRelation",new DataColumn[]{SupplierIdColumn}, new DataColumn[]{RelatedProductCollection.SupplierIdColumn});
					SubDomain.Relations.Add(supplierProductRelation);
				}
			}

		}

		bool _handlingError = false;
		/// <summary>
		/// Determines if errors are handled by this object
		/// </summary>
		public override bool HandleErrors()
		{
			if (_handlingError) return false;
			_handlingError = true;
			try
			{
			return false;
			}
			catch
			{
				throw;
			}
			finally
			{
				_handlingError = false;
			}
		}
		#endregion 

		#region Helper Methods

		internal virtual string GetPrimaryKeyXml()
		{
			return GetPrimaryKeyXml(((IEnumerable<ACME.Northwind.Business.Objects.Supplier>)new ACME.Northwind.Business.Objects.SupplierCollection(this)).Select(x => x.PrimaryKey));
		}

		internal static string GetPrimaryKeyXml(ACME.Northwind.Business.Objects.SupplierPrimaryKey primaryKey)
		{
			List<ACME.Northwind.Business.Objects.SupplierPrimaryKey> list = new List<ACME.Northwind.Business.Objects.SupplierPrimaryKey>();
			list.Add(primaryKey);
			return GetPrimaryKeyXml(new List<ACME.Northwind.Business.Objects.SupplierPrimaryKey>(list));
		}

		internal static string GetPrimaryKeyXml(IEnumerable<ACME.Northwind.Business.Objects.SupplierPrimaryKey> primaryList)
		{
			StringWriter sWriter = new StringWriter();
			XmlTextWriter xWriter = new XmlTextWriter(sWriter);
			xWriter.WriteStartDocument();
			xWriter.WriteStartElement("SuppliersList");
			foreach(ACME.Northwind.Business.Objects.SupplierPrimaryKey primaryKey in primaryList)
			{
				xWriter.WriteStartElement("Suppliers");
				xWriter.WriteStartElement("SupplierID");
				xWriter.WriteString(primaryKey.SupplierId.ToString());
				xWriter.WriteEndElement();
				xWriter.WriteEndElement();
			}
			xWriter.WriteEndElement();
			xWriter.WriteEndDocument();
			xWriter.Flush();
			xWriter.Close();
			return sWriter.ToString();
		}

		#endregion

		#region Methods

		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
		}

		#endregion

	}
	#endregion

}
